<template>
  <div style="margin-top:16px;background-color:#ffffff;border-radius: 6px;padding:20px">
    <a-space class="operator" style="margin-bottom:20px;">
      <a-button type="primary" @click="copy">复制创意</a-button>
    </a-space>
    <standard-table
      showAlert
      :loading='loading'
      :columns="columns"
      :dataSource="dataSource"
      :pagination="false"
      :selectedRows.sync="selectedRowKeys"
      @selectedRowChange="selectedRowChange"
      @clear="onClear"
      @change="onChange"
    >
      <div slot="danyuan" slot-scope="{record}">
        <div v-if="record.material.video_url" >
          <video width="260" height="146" controls>
            <source :src="record.material.video_url" type="video/mp4">
          </video>
        </div>
        <div v-else >
          <img style="width:260px;height:146px;" :src="record.material.pictures[0].image" alt="">
        </div>
      </div>
      <div slot="biaoti" slot-scope="{record}">
        {{record.material.title}}
      </div>
      <div slot="status" slot-scope="{record}">
        <div style="display:flex;align-items: center;">
          <div style="width:6px;height:6px;border-radius:50%;background-color:#00cc63" v-if="record.status==0"></div>
          <div style="width:6px;height:6px;border-radius:50%;background-color:#ff7875" v-else></div>
          <span style="margin-left:5px">{{record.status | setStatus}}</span>
        </div>
      </div>
      <div slot="subject" slot-scope="{record}">
        <div style="display:flex;align-items: center;">
          <span style="margin-left:5px">{{record.subject | setSubject}}</span>
        </div>
      </div>
      <div slot="action" slot-scope="{record}">
        <!-- <a style="margin-right: 8px">
          <a-icon type="edit"/>编辑
        </a> -->
        <a-popconfirm title="确定删除？" ok-text="删除" cancel-text="取消" @confirm='deleteRecord(record.creativeFeedId)'>
          <a href="javascript:;">
            <a-icon type="delete" />删除
          </a>
        </a-popconfirm>
      </div>
    </standard-table>
    <a-modal v-model="showChooseChuangyi" title="选择目标单元" :width="620" okText="复制" @ok="fuzhi" :confirm-loading="fuzhiLoading" >
      <div style="max-height:640px;overflow-y:auto">
        <div class="area" style="margin-bottom:20px;">
          <a-input-search :loading="searchLoading" style="width:300px;" placeholder="搜索计划名称" enter-button @search="onDanyuanSearch" />
        </div>
        <a-tree v-model="chedkedKeys" :expandedKeys.sync="expandedKeys" :tree-data="treeData" :replaceFields="{title:'campaignFeedName'}" @check="onCheck" checkable defaultExpandAll>
          <div slot="slot" class="line1" :class="item.mod=='danyuan'?'treeItem2':'treeItem'" slot-scope="item" @click="treeClick(item)">
            <span v-if="item.mod == 'home'">{{item.campaignFeedName}}</span>
            <span v-if="item.mod == 'jihua'">{{item.campaignFeedName}}</span>
            <span v-if="item.mod == 'danyuan'">{{item.adgroupFeedName}}</span>
          </div>
        </a-tree>
        <!-- <a-checkbox-group @change="e => danyuanCheckedId = e">
          <a-row>
            <a-col :span="24" v-for="(item,index) in danyuanList" :key="index">
              <a-checkbox :value="item.adgroupFeedId">{{item.adgroupFeedName}}</a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group> -->
      </div>
    </a-modal>
  </div>
</template>

<script>
import StandardTable from '@/components/table/StandardTable'
import { getCreativeFeed } from '@/api/xinxiliu/chuangyi'
import { getCampaignFeed } from '@/api/xinxiliu/jihua'
import { getAdgroupFeed } from '@/api/xinxiliu/danyuan'
import { copyCreativeToSelf, deleteCreativeFeed } from '@/api/xinxiliu/getBaidu'


export default {
  name:'danyuanView',
  data(){
    return{
      dataSource:[],
      selectedRows:[],
      danyuanCheckedId:[],
      danyuanList:[],
      expandedKeys:['0'],
      chedkedKeys:[],
      treeData:[],
      danyuan_search:'',
      loading:false,
      showChooseChuangyi:false,
      fuzhiLoading:false,
      searchLoading:false,
      selectedRowsForId:[],
      selectedRowKeys:[],
      columns:[
        {
          title: '创意单元',
          // width:240,
          fixed:'left',
          dataIndex: 'adgroupFeedName',
          // defaultSortOrder: 'descend',
          scopedSlots: { customRender: 'danyuan' },
          sorter: (a, b) => new Date(a.addtime).valueOf() - new Date(b.addtime).valueOf(),
        },
        {
          title: '创意标题', 
          scopedSlots: { customRender: 'biaoti' },
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          width:100,
          fixed:'right',
          scopedSlots: { customRender: 'action' }
        },
      ]
    }
  },
  props:{
    adgroupFeedId: {
      type:[Number,String],
      default:0
    },
  },
  created(){
    // console.log('create-chuangyi',this.adgroupFeedId)
    this.getChuangyi(this.adgroupFeedId)
  },
  methods:{
    getChuangyi(id){
      console.log('watch-danyuanView',id)
      this.loading = true;
      const _this = this;
      let params = {
        ids:[id],
        idType:2 // 1 - 计划类型 2 - 单元类型
      }
      getCreativeFeed(params).then((e) => {
        _this.loading = false;
        if(e.errcode == 0){
          let data = e.data.body.data
          let key = 1
          for(let i of data){
            i.material = JSON.parse(i.material)
            i.key = key
            key++;
          }
          _this.dataSource = data
          console.log(data)
        }
      }).catch(()=>{
        _this.loading = false
      })
    },
    getCampaignFeed(){
      if(this.danyuan_search == ''){
        this.$message.error('请输入搜索内容')
        return false
      }
      this.searchLoading = true
      getCampaignFeed({}).then(e=>{
        if(e.errcode == 0){
          let key = 1;
          let expandedKeys = []
          let ids = []
          e.data.body.data = e.data.body.data.filter(e=>e.campaignFeedName.indexOf(this.danyuan_search) != -1)
          for(let i of e.data.body.data){
            i.key = key;
            i.scopedSlots = {title: 'slot'}
            ids.push(i.campaignFeedId)
            i.mod = 'jihua'
            expandedKeys.push(key)
            key++
          }
          this.expandedKeys = expandedKeys
          let children = e.data.body.data
          if(ids.length > 0){
            let danyuanCheckedId = []
            getAdgroupFeed({ids}).then((res) => {
              console.log(res)
              this.searchLoading = false
              if(res.errcode == 0){
                let data = res.data.body.data
                for(let i of data){
                  i.scopedSlots = {title: 'slot'}
                  i.mod = 'danyuan'
                  danyuanCheckedId.push(i.adgroupFeedId)
                }
                for(let item of children){
                  item.children = data.filter(e=>e.campaignFeedId == item.campaignFeedId)
                }
                this.danyuanCheckedId = danyuanCheckedId
                this.danyuanList = res.data.body.data 
                this.treeData = children
              }
            }).catch(()=>{
              this.searchLoading = false
            })
          }else{
            this.searchLoading = false
            this.$message.error('没有匹配的搜索项')
          }
        }
      }).catch(()=>{
        this.searchLoading = false
      })
    },
    copy(){
      if(this.selectedRowsForId.length > 0){
        this.showChooseChuangyi = true
      }else{
        this.$message.error('请选择需要复制的计划')
      }
    },
    fuzhi(){
      console.log(this.danyuanCheckedId,this.selectedRowsForId)
      if(this.danyuanCheckedId.length > 0){
        let params = {
          destAdgroupIds: this.danyuanCheckedId.join(','),
          sourceCreativeIds: this.selectedRowsForId.join(',')
        }
        this.fuzhiLoading = true
        copyCreativeToSelf(params).then((res) => {
          this.fuzhiLoading = false
          if(res.errcode == 0){
            this.showChooseChuangyi = false
            this.$message.success('复制成功')
          }
        }).catch(()=>{
          this.fuzhiLoading = false
        });
      }else{
        this.$message.error('请选择目标单元')
      }
    },
    onCheck(checkedKeys, e){
      console.log(checkedKeys)
      let checked_adgroupFeedId = []
      for(let i of e.checkedNodes){
        let adgroupFeedId = i.data.props.adgroupFeedId
        if(adgroupFeedId){
          checked_adgroupFeedId.push(adgroupFeedId)
        }
      }
      this.danyuanCheckedId = checked_adgroupFeedId
    },
    onDanyuanSearch(e){
      this.danyuan_search = e
      this.getCampaignFeed()
    },
    edit(){

    },
    deleteRecord(creativeFeedId){
      console.log(creativeFeedId)
      const _this = this;
      const hideLoding = _this.$message.loading('删除中')
      deleteCreativeFeed({creativeFeedIds:creativeFeedId}).then((e) => {
        if(e.errcode == 0){
          hideLoding()
          _this.$message.success('删除成功')
          _this.getChuangyi(this.adgroupFeedId)
        }
      });
    },
    selectedRowChange(selectedRowKeys, selectedRows){
      // console.log('selectedRowChange',selectedRowKeys, selectedRows)
      this.selectedRowsForId = selectedRows.map(e=>e.creativeFeedId)
      console.log(this.selectedRowsForId)
    },
    onChange(e){
      console.log('onChange',e)
    },
    onClear(e){
      console.log('onClear',e)
    },
  },
  watch:{
    adgroupFeedId(e){
      this.getChuangyi(e)
    }
  },
  filters:{
    setStatus(e){
      switch(e){
        case 0: case '0':
          return '有效'
        case 1: case '1':
          return '暂停推广'
        case 2: case '2':
          return '审核中'
        case 3: case '3':
          return '审核未通过'
        case 4: case '4':
          return '无效'
      }
    },
    setSubject(e){
      switch(e){
        case 1: case '1':
          return '网站链接'
        case 2: case '2':
          return '应用下载（IOS）'
        case 3: case '3':
          return '应用下载（Android）'
        case 7: case '7':
          return '电商店铺'
      }
    }
  },
  components:{
    StandardTable,
  }
}
</script>

<style lang="less" scoped>
  
</style>